package com.ldq.imooc.basics.multiThread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author : 李道泉
 * @Description :
 * @Date : 2018/4/24 15:51
 * @Modified by :
 */
public class VolatileDemo {

    private Lock lock = new ReentrantLock();
    //    private volatile int number = 0;
    private int number = 0;

    public int getNumber() {
        return this.number;
    }

    public synchronized void increase1() {

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.number++;
    }

    public void increase() {

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //1.synchronized
//        synchronized (this) {
//            this.number++;
//        }
        //2.ReentrantLock
        lock.lock();
        try {
            this.number++;
        } finally {
            //释放锁
            lock.unlock();
        }
    }

    public static void main(String[] args) {

        final VolatileDemo demo = new VolatileDemo();

        for (int i = 0; i < 500; i++) {

            new Thread(new Runnable() {
                @Override
                public void run() {
                    demo.increase();
                }
            }).start();
        }
        //如果还有子线程在运行，主线程就让出CPU资源，直至所有线程运行完毕，主线程再继续执行
        while (Thread.activeCount() > 1) {
            Thread.yield();
        }
        System.out.println("number：" + demo.getNumber());
    }
}
